using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UniversalAdmin.Application.Dto;
using UniversalAdmin.Application.Commands;
using System.Linq;
using UniversalAdmin.Domain.Entities.App;
using UniversalAdmin.Domain.Repositories;

namespace UniversalAdmin.Application.Services;

public partial class AppUserRoleMappingServices : IAppUserRoleMappingServices
{
    private readonly IRepository<AppUser> _userRepository;
    private readonly IRepository<AppRole> _roleRepository;

    public AppUserRoleMappingServices(IRepository<AppUser> userRepository, IRepository<AppRole> roleRepository)
    {
        _userRepository = userRepository;
        _roleRepository = roleRepository;
    }

    public async Task<ApiResult<IEnumerable<string>>> GetUserRolesAsync(Guid userId)
    {
        var user = await _userRepository.GetByIdAsync(userId);
        if (user == null) return ApiResult<IEnumerable<string>>.Failed(404, "用户不存在");
        var roles = user.Roles.Select(r => r.RoleName);
        return ApiResult<IEnumerable<string>>.Success(roles);
    }

    public Task AssignRoleToUserAsync(Guid userId, Guid roleId)
    {
        // TODO: 实现分配角色逻辑
        return Task.CompletedTask;
    }

    public async Task<ApiResult> RemoveUserRoleAsync(Guid userId, Guid roleId)
    {
        var user = await _userRepository.GetByIdAsync(userId);
        if (user == null) return ApiResult.Failed(404, "用户不存在");
        var role = user.Roles.FirstOrDefault(r => r.Id == roleId);
        if (role == null) return ApiResult.Failed(404, "角色不存在");
        user.Roles.Remove(role);
        await _userRepository.UpdateAsync(user);
        return ApiResult.Success("移除成功");
    }

    public async Task<ApiResult> AssignRolesAsync(Guid userId, List<Guid> roleIds)
    {
        var user = await _userRepository.GetByIdAsync(userId);
        if (user == null) return ApiResult.Failed(404, "用户不存在");

        // 需要 _roleRepository，假设已注入
        var roles = _roleRepository.All.Where(r => roleIds.Contains(r.Id) && !r.IsDelete).ToList();
        if (roles.Count != roleIds.Count)
            return ApiResult.Failed(404, "部分角色不存在或已被删除");

        user.Roles.Clear();
        foreach (var role in roles)
            user.Roles.Add(role);

        await _userRepository.UpdateAsync(user);
        return ApiResult.Success("分配用户角色成功");
    }
} 